package com.mlethe.library.net.retrofit;

import com.mlethe.library.net.retrofit.interceptor.MoreBaseUrlInterceptor;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * Created by Mlethe on 2018/6/6.
 */
public final class RetrofitClient {

    private Retrofit retrofit;

    private RetrofitClient() {
    }

    private static final class Holder {
        private static final RetrofitClient INSTANCE = new RetrofitClient();
    }

    private static RetrofitClient getInstance() {
        return Holder.INSTANCE;
    }

    public static <T> T create(final Class<T> service) {
        return getInstance().retrofit.create(service);
    }

    public final static class Builder {
        private String baseUrl;

        private OkHttpClient.Builder okHttpBuilder;

        private Retrofit.Builder retrofitBuilder;

        /**
         * 设置 baseUrl
         *
         * @param baseUrl
         * @return
         */
        public Builder setBaseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
            return this;
        }

        /**
         * 设置 OKHttpClient
         *
         * @param builder
         * @return
         */
        public Builder setOkHttpClient(OkHttpClient.Builder builder) {
            okHttpBuilder = builder;
            return this;
        }

        /**
         * 设置 Retrofit
         *
         * @param builder
         * @return
         */
        public Builder setRetrofit(Retrofit.Builder builder) {
            retrofitBuilder = builder;
            return this;
        }

        public void build() {
            OkHttpClient okHttpClient = okHttpBuilder.addInterceptor(new MoreBaseUrlInterceptor())
                    .build();
            getInstance().retrofit = retrofitBuilder.baseUrl(baseUrl)
                    .client(okHttpClient)
                    .build();
            baseUrl = null;
            okHttpBuilder = null;
            retrofitBuilder = null;
        }
    }
}
